﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Point : MonoBehaviour {
	public Vector3 initialPos;		//初始位置
	public Vector3 aimPos;			//目标位置
	public float radius;			//点的半径
	public int segments;			//分段数
	public float speed;				//速度
	public Color color;				//颜色


	public Shader shader;

	private Mesh mesh;
	private Vector3[] points;
	private int[] triangles;

	// Start is called before the first frame update
	void Start() {
		initialPos = transform.position;
		//aimPos = transform.position;

		gameObject.AddComponent<MeshFilter>();
		gameObject.AddComponent<MeshRenderer>();
		mesh = GetComponent<MeshFilter>().mesh;
		GetComponent<MeshRenderer>().material.color = color;
		GetComponent<MeshRenderer>().material.shader = shader;
		mesh.Clear();
	}

	// Update is called once per frame
	void Update() {

	}

	private void FixedUpdate() {
		//GetComponent<MeshRenderer>().material.color = color;
		//GetComponent<MeshRenderer>().material.shader = shader;
		if ((aimPos - transform.position).magnitude > 0.001f * (aimPos - initialPos).magnitude) {
			transform.position = transform.position + (aimPos - initialPos) * speed * Time.deltaTime;
		}

		DrawCircle(radius, segments);
	}

	public void ChangeAimPos(float x, float y) {
		initialPos = transform.position;
		aimPos = new Vector3(x, y);
	}

	/// <summary>
	/// 画圆
	/// </summary>
	/// <param name="radius">圆的半径</param>
	/// <param name="segments">圆的分段数</param>
	void DrawCircle(float radius, int segments) {
		//顶点
		points = new Vector3[segments + 1];
		points[0] = gameObject.transform.position;
		float deltaAngle = Mathf.Deg2Rad * 360f / segments;
		float currentAngle = 0;
		for (int i = 1; i < points.Length; i++) {
			float cosA = Mathf.Cos(currentAngle);
			float sinA = Mathf.Sin(currentAngle);
			points[i] = new Vector3(cosA * radius + gameObject.transform.position.x,
				sinA * radius + gameObject.transform.position.y, 0);
			currentAngle += deltaAngle;
		}

		//三角形
		triangles = new int[segments * 3];
		for (int i = 0, j = 1; i < segments * 3 - 3; i += 3, j++) {
			triangles[i] = 0;
			triangles[i + 1] = j + 1;
			triangles[i + 2] = j;
		}
		triangles[segments * 3 - 3] = 0;
		triangles[segments * 3 - 2] = 1;
		triangles[segments * 3 - 1] = segments;


		Mesh mesh = GetComponent<MeshFilter>().mesh;
		mesh.Clear();

		mesh.vertices = points;
		mesh.triangles = triangles;
	}
}
//计科1702 夏泽坤 170950119